package com.huazh.service;

import com.huazh.bean.Account;
import com.huazh.feign.UserServiceClient;
import com.huazh.mapper.AccountMapper;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @ClassName:AccountService
 * @Description://TODO
 * @Authoe: hzh
 * @Time: 2020/7/3011:34
 */
@Service
public class AccountService {

    @Resource
    private AccountMapper accountMapper;
    @Resource
    private UserServiceClient userServiceClient;

    public Account  queryById(Long id){
        return accountMapper.queryById(id);
    }

    @GlobalTransactional
    public Account add(String userName){
        System.out.println("开始全局事务。XID="+ RootContext.getXID());
        if(null == RootContext.getXID()){
            throw new RuntimeException("分布式事务全局xid为null");
        }
        //新建用户账号
        Account account = new Account();
        account.setId((long)(1+Math.random()*1000));
        account.setUserName(userName);
        account.setName(userName);
        accountMapper.add(account);
        //创建用户角色
        userServiceClient.add(account.getId(), userName);

        int data = 10/0;
        //锁住账号
        accountMapper.updateLocked(account.getId());

        System.out.println(account.getId());
        return account;
    }
}
